from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template


from ft_table import ft
import logging, model, os
class ManageHandler(webapp.RequestHandler):
    def get(self):
        action = self.request.get('action')
        if action=='flush-memcache':
            memcache.flush_all()
            logging.info('flush memcache')
            self.response.out.write('memache is flushed.')
        elif action=='exe_failed_sql':
            self.exe_failed_sql()
        else:
            path = os.path.join(os.path.dirname(__file__), 'template/manage.html')
            self.response.out.write(template.render(path, {'flush_memcache': 'flush-memcache', 'exe_failed_sql': 'exe_failed_sql'}))
    
    def exe_failed_sql(self):
        '''
        scan the SqlReqeust table and execute the failed sql
        '''
        f = ft(None, None)
        results = []
        for s in model.SqlRequest.all().filter('status =', 'new'):
            
            t = s.transaction_ref
            if t:
                desc = t.description
            else:
                desc = ''
            result = {'description': desc, 'sql': s.sql, 'status': 'Failed again'}
            try:
                f.SqlQuery(s.sql, t)
                result['status'] = 'success'
            except:
                pass
            s.delete()
            
            results.append(result)
        
        
        
        path = os.path.join(os.path.dirname(__file__), 'template/sql_list.html')
        self.response.out.write(template.render(path, {'results': results}))
            
            
        
            